package in.srain.cube.request;

/**
 * @author http://www.liaohuqiu.net
 */
public class SimpleRequest<T, OriginDataType> extends RequestBase<T, OriginDataType> {

    protected RequestHandler<T, OriginDataType> mRequestHandler;
    protected RequestFinishHandler<T> mRequestFinishHandler;

    public SimpleRequest() {
    }

    public SimpleRequest(RequestHandler<T, OriginDataType> handler) {
        setRequestHandler(handler);
    }

    @Override
    protected void doSendRequest() {
        RequestManager.getInstance().getRequestProxy(this).sendRequest(this);
    }

    @Override
    protected T doRequestSync() throws Throwable {
        return (T) RequestManager.getInstance().getRequestProxy(this).requestSync(this);
    }

    @Override
    protected void prepareRequest() {
        RequestManager.getInstance().getRequestProxy(this).prepareRequest(this);
    }

    @Override
    public void onRequestSuccess(T data) {
        if (mRequestHandler != null) {
            mRequestHandler.onRequestFinish(data);
        }
        if (mRequestFinishHandler != null) {
            mRequestFinishHandler.onRequestFinish(data);
        }
    }

    @Override
    public void onRequestFail(Object requestTag, FailData failData) {
        RequestManager.getInstance().getRequestProxy(this).onRequestFail(this, requestTag, failData);
        if (mRequestHandler != null) {
            mRequestHandler.onRequestFail(failData);
        }
        if (mRequestFinishHandler != null) {
            mRequestFinishHandler.onRequestFail(failData);
        }
    }

    @Override
    public T processOriginDataFromServer(OriginDataType originData) {
        if (mRequestHandler != null) {
            return mRequestHandler.processOriginData(originData);
        }
        return null;
    }

    public RequestFinishHandler<T> getRequestFinishHandler() {
        return mRequestFinishHandler;
    }

    public void setRequestFinishHandler(RequestFinishHandler<T> requestFinishHandler) {
        mRequestFinishHandler = requestFinishHandler;
    }

    public RequestHandler<T, OriginDataType> getRequestHandler() {
        return mRequestHandler;
    }

    public SimpleRequest setRequestHandler(RequestHandler<T, OriginDataType> handler) {
        mRequestHandler = handler;
        return this;
    }

    public SimpleRequest setRequestHandler(RequestFinishHandler<T> finishHandler, RequestHandler<T, OriginDataType> handler) {
        mRequestFinishHandler = finishHandler;
        mRequestHandler = handler;
        return this;
    }
}
